package Controller;

import DataAccess.CustomerFacade;
import DataAccess.util.JsfUtil;
import DataAccess.util.PaginationHelper;
import Model.Citys;
import Model.County;
import Model.Customer;
import Model.User;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;

@ManagedBean(name = "customerController")
@SessionScoped
public class CustomerController implements Serializable {

    private Customer current;
    private DataModel items = null;
    @EJB
    private DataAccess.CustomerFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private String registeredState;

    public CustomerController() {
    }

    public Customer getSelected() {
        if (current == null) {
            current = new Customer();
            selectedItemIndex = -1;
        }
        EntityManager entityManager =  Persistence.createEntityManagerFactory("KitapcdappPU").createEntityManager();
        Query query = entityManager.createNamedQuery("Customer.findAll");
        List<Customer> customerList = (List<Customer>) query.getResultList();
        int id = customerList.size();
        current.setId(id + 1);
        Date date = new Date();
        current.setCreateddate(date);
        return current;
    }

    private CustomerFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Customer) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Customer();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CustomerCreated"));
            registeredState = "success";
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            registeredState = "success";
            return null;
        }
    }
    
    public String prepareEdit() {
        current = (Customer) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }
    
    public void prepareEditForUserpage(ActionEvent event) {
        String username = (String)event.getComponent().getAttributes().get("username");
        EntityManager entityManager =  Persistence.createEntityManagerFactory("KitapcdappPU").createEntityManager();
        Query query = entityManager.createNamedQuery("Customer.findByCustomerUsername");
        query.setParameter("username", username);
        List<Customer> customer = (List<Customer>)query.getResultList();
        current = customer.get(0);
    }
    

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage("Başarıyla güncellendi");
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage("Hata Oluştu");
            return null;
        }
    }
    
    public String updateForUserPage() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage("Başarıyla güncellendi");
            return "mainpage";
        } catch (Exception e) {
            JsfUtil.addErrorMessage("Hata Oluştu");
            return "userPage";
        }
    }

    public String destroy() {
        current = (Customer) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CustomerDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    //bu da kodlar
    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }
    
    public List<Citys> getCitys() {
        EntityManager entityManager2 =  Persistence.createEntityManagerFactory("KitapcdappPU").createEntityManager();
        Query query = entityManager2.createNamedQuery("Citys.findAll");
        List<Citys> cityList = (List<Citys>) query.getResultList();
        return cityList;
    }
    
    public List<County> getCountys() {
        EntityManager entityManager3 =  Persistence.createEntityManagerFactory("KitapcdappPU").createEntityManager();
        List<County> countyList = null;
        Query query = entityManager3.createNamedQuery("County.findAll");
        /*if(cityid != null) {
            query = entityManager.createNamedQuery("County.findAllByCityId");
            Citys c = new Citys();
            c.setId(cityid.getCitycode());
            query.setParameter("cityid", c);
            countyList = (List<County>) query.getResultList();
        } else {
            return null; 
        }*/
        countyList = (List<County>) query.getResultList();
        return countyList;
    }
    
    public void registerUser() {
        if(isExistUser() == 0) {
            EntityManager entityManager =  Persistence.createEntityManagerFactory("KitapcdappPU").createEntityManager();
            Query query = entityManager.createNamedQuery("Customer.findAll");
            List<Customer> customerList = (List<Customer>) query.getResultList();
            int id = customerList.size();
            current.setId(id + 1);
            Date date = new Date();
            current.setCreateddate(date);
            User user = new User(current.getId(), current.getUsername(), current.getPassword());
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", user);
            create();
        } else {
            addMessage("Hata", "Bu kullanıcı adı veya mail adresiyle kayıt bulunmaktadır.");
            registeredState = "error";
        }
    }
    
    
    public int isExistUser() {
        EntityManager entityManager =  Persistence.createEntityManagerFactory("KitapcdappPU").createEntityManager();
        Query query = entityManager.createNamedQuery("Customer.findByForRegister");
        query.setParameter("username", current.getUsername());
        query.setParameter("email", current.getEmail());
        List<Customer> customerList = (List<Customer>) query.getResultList();
        return customerList.size();
    }
    
    public String goToMainpage() {
        if(registeredState.matches("success")) {
            User user = new User(current.getId(), current.getUsername(), current.getPassword());
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", user);
            return "mainpage";
        } else {
            return "login";
        }
    }
    
    private void addMessage(String summary, String detail) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary, detail);
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

    @FacesConverter(forClass = Customer.class)
    public static class CustomerControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            CustomerController controller = (CustomerController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "customerController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }
        List<SelectItem> countyListByCity = new ArrayList<SelectItem>();

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Customer) {
                Customer o = (Customer) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Customer.class.getName());
            }
        }
    }
}
